import Taro, { useEffect, useState, useDidHide } from '@tarojs/taro'
import { View, Swiper, SwiperItem, Image, Text } from '@tarojs/components'
import './index.scss'

const backgroundAudioManager = Taro.getBackgroundAudioManager()


export default function RPlayer({ recordingData }) {
  const [current, setCurrent] = useState(0)
  const [curSentenceText, setCurSentenceText] = useState('')
  const [isPlaying, setIsPlaying] = useState(false)
  let timmer

  useEffect(() => {
    if (recordingData.audioUrl) {
      // backgroundAudioManager.title = recordingData.audioShareRecordingData.book
      // backgroundAudioManager.src = recordingData.audioUrl
      // backgroundAudioManager.pause()
      initSingleAudio()
    }

    console.log(backgroundAudioManager)

    return () => {
      backgroundAudioManager.stop()
    }

  }, [recordingData])

  function initSingleAudio() {

    backgroundAudioManager.onPlay(() => {
      setIsPlaying(true)

      timmer = setInterval(() => {
        let curTime = backgroundAudioManager.currentTime
        // let duration = backgroundAudioManager.duration

        // image
        let imageIndex = 0;
        for (; imageIndex < recordingData.imageKeyTimeArray.length; imageIndex++) {
          let imageKeyTime = recordingData.imageKeyTimeArray[imageIndex];
          if (curTime < Number(imageKeyTime.time)) {
            break;
          }
        }
        //当前页
        let curImageIndex = imageIndex - 1;
        if (curImageIndex < 0) curImageIndex = 0;

        if (current != Number(curImageIndex)) {
          setCurrent(Number(curImageIndex));
        }

        // sentence
        let sentenceIndex = 0;
        for (; sentenceIndex < recordingData.sentenceTimeArray.length; sentenceIndex++) {
          let sentenceTime = recordingData.sentenceTimeArray[sentenceIndex];
          if (curTime < Number(sentenceTime.time)) {
            break;
          }
        }
        //当前页
        let curSentenceIndex = sentenceIndex - 1;
        if (curSentenceIndex < 0) curSentenceIndex = 0;
        let __curSentenceText = recordingData.sentenceTimeArray[curSentenceIndex].text;
        setCurSentenceText(__curSentenceText);
      }, 500)
    })

    //end
    backgroundAudioManager.onEnded( () => {
      audioFinish()
    });

    //end
    backgroundAudioManager.onStop( () => {
      audioFinish()
    })

    backgroundAudioManager.onPause(() =>{
      clearInterval(timmer)
      setIsPlaying(false)
    })
  }

  function audioFinish() {
    timmer && clearInterval(timmer);// 停止定时器
    setCurSentenceText('') // 清空字幕
    setCurrent(0)
    setIsPlaying(false)
  }

  function play() {
    console.log(123123123)
    backgroundAudioManager.title = recordingData.audioShareRecordingData.book || ' '
    // backgroundAudioManager.src = recordingData.audioUrl
    const _url = recordingData.audioUrl.split('.com/')
    const _source = _url[1].split('/').map(s => (encodeURIComponent(s))).join('/')
    const audioUrl = `${_url[0]}.com/${_source}`
    backgroundAudioManager.src = audioUrl
    console.log(audioUrl)
    console.log(_source)
    console.log(_url)
    // backgroundAudioManager.src = 'http://wsaudio.bssdlbig.kugou.com/1912130930/A4e4SPDuNjrEzaknykEUDw/1576287011/bss/extname/wsaudio/209caccd5efa63c5388ac0b1ae7cedc3.mp3'
    // backgroundAudioManager.src = 'https://user.read1000.com/user/1204/recording/Young+Sheldon+%e5%b0%8f%e8%b0%a2%e5%b0%94%e9%a1%bf/S1E01/20191213-093755-048.mp3'
    backgroundAudioManager.play()
    backgroundAudioManager.onError((e) => {
      console.log(e)
    })
    console.log(backgroundAudioManager)
  }

  useDidHide(() => {
    audioFinish()
  })

  return (
    <View className='player-container'>
      <View className='player-wrapper'>
        <Swiper
          // indicatorDots={false}
          // autoplay={false}
          current={current}
          className='swiper-container'
        >
          {
            recordingData.imageKeyTimeArray.map((img, index) => (
              <SwiperItem key={index} catchtouchmove={() => {return false}}>
                <View className='img-wrapper'>
                  <Image className='img' src={img.imgUrl} mode='aspectFit'></Image>
                </View>
              </SwiperItem>
            ))
          }


        </Swiper>
        <Text className='sentence-container'>{curSentenceText}</Text>

        {
          !isPlaying && <Image className='play-icon' src={require('../../assets/icon_play.png')} onClick={() => play()}></Image>
        }
      </View>

      <View className='comment-container'>

      </View>
    </View>
  )
}

